package cn.eonshine.cuba.lsms.modular.basic.service.impl;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import cn.eonshine.cuba.inf.common.util.DateUtils;
import cn.eonshine.cuba.inf.common.http.InfStatus;
import cn.eonshine.cuba.inf.modular.basic.entity.Oil;
import cn.eonshine.cuba.lsms.modular.CommonService;
import cn.eonshine.cuba.lsms.modular.basic.entity.OilInfo;
import cn.eonshine.cuba.lsms.modular.basic.service.IOilInfoService;
import cn.eonshine.cuba.lsms.modular.basic.service.IOilService;

@Service
public class OilService extends CommonService<Oil> implements IOilService {

	@Autowired
	private IOilInfoService infoService;

	private final String listUrl = "/oil/list";
	private final String updateUrl = "/oil/update";
	
	@Override
	public void requestOil() {
		requestData(listUrl, updateUrl, InfStatus.INF_LOG_TYPE.PRODUCT_NUM);
	}
	
	
	@Override
	protected Object dataHandle(Oil oil) throws Exception {
		QueryWrapper<OilInfo> entity = new QueryWrapper<OilInfo>();
		entity.eq("OIL_CODE", StringUtils.trim(oil.getOilCode()));
		OilInfo info = infoService.getOne(entity);
		boolean isInsert = false;
		if(info == null) {
			info = new OilInfo();
			isInsert = true;
		}
		info.setOilCode(StringUtils.trim(oil.getOilCode()));
		info.setOilName(StringUtils.trim(oil.getOilName()));
		info.setFullName(StringUtils.trim(oil.getFullName()));
		if(StringUtils.isNotBlank(oil.getEnable())) {
			info.setEnable(oil.getEnable());
		}else {
			info.setEnable(InfStatus.USEABLE_YES);
		}
		
		if(info.getOilIdUm() == null) {
			info.setOilIdUm(BigDecimal.valueOf(1l));
		}
		info.setCreateBy(InfStatus.CREATE_BY);
		info.setUpdateBy(InfStatus.UPDATE_BY);
		info.setRemarks(oil.getRemarks());
		info.setIsFromInf(InfStatus.IS_FROM_INTERFACE);
		
		
		Date nowTime = DateUtils.getCubaDate(Calendar.getInstance().getTime());
		if(isInsert) {
			info.setCreateDate(nowTime);
		}
		info.setUpdateDate(nowTime);
		
		if(isInsert) {
			infoService.save(info);
		}else {
			infoService.updateById(info);
		}
		return info;
	}
	
	@Override
	protected List<Oil> feadBackDataHandle(Object obj, Oil oil, List<Oil> feadBackDataLists) throws Exception {
		OilInfo info = (OilInfo) obj;
		// 返回进行更新的数据
		Oil tmpBack = new Oil();
		tmpBack.setOilCode(oil.getOilCode());
		tmpBack.setDataInputDatetime(oil.getDataInputDatetime());
		tmpBack.setLsmsUpdate(InfStatus.LSMS_UPDATE_EXTRACT_YES);
		tmpBack.setId(info.getId());  // lsms id
		tmpBack.setOilName(StringUtils.trim(oil.getOilName()));
		feadBackDataLists.add(tmpBack);
		return feadBackDataLists;
	}

}
